'use client'

import React, { createContext, useContext, useEffect, useRef, useState } from 'react'
import { UniverSheetsCorePreset } from '@univerjs/preset-sheets-core'
import UniverPresetSheetsCoreEnUS from '@univerjs/preset-sheets-core/locales/en-US'
import UniverPresetSheetsCoreZhCN from '@univerjs/preset-sheets-core/locales/zh-CN'
import { createUniver, LocaleType, mergeLocales, Univer } from '@univerjs/presets'
import '@univerjs/preset-sheets-core/lib/index.css'
// 导入插件
import ImportCSVPlugin from '@/plugins/ImportCSVPlugin'
import ImportExcelPlugin from '@/plugins/ImportExcelPlugin'
import ExportPlugin from '@/plugins/ExportPlugin'

interface UniverContextType {
  univer: Univer | null
  univerAPI: any
  isReady: boolean
}

const UniverContext = createContext<UniverContextType>({
  univer: null,
  univerAPI: null,
  isReady: false
})

interface UniverProviderProps {
  children: React.ReactNode
  containerId?: string
  sheetId?: string
}

export const UniverProvider: React.FC<UniverProviderProps> = ({ 
  children, 
  containerId = 'univer-container',
  sheetId 
}) => {
  const [univer, setUniver] = useState<Univer | null>(null)
  const [univerAPI, setUniverAPI] = useState<any>(null)
  const [isReady, setIsReady] = useState(false)
  const containerRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    console.log('UniverProvider useEffect triggered')
    console.log('containerRef.current:', containerRef.current)
    
    // 延迟初始化，确保DOM已渲染
    const initTimer = setTimeout(() => {
      console.log('Starting Univer initialization...')
      
      if (!containerRef.current) {
        console.log('Container not ready after timeout')
        return
      }

      try {
        console.log('Creating Univer instance...')
        const { univer: univerInstance, univerAPI: api } = createUniver({
          locale: LocaleType.ZH_CN,
          locales: {
            [LocaleType.EN_US]: mergeLocales(
              UniverPresetSheetsCoreEnUS,
            ),
            [LocaleType.ZH_CN]: mergeLocales(
              UniverPresetSheetsCoreZhCN,
            ),
          },
          presets: [
            UniverSheetsCorePreset({
              container: containerRef.current,
              header: true,
              toolbar: true,
              footer: {
                sheetBar: true,
                statisticBar: true,
                menus: true,
                zoomSlider: true
              },
              contextMenu: true,
              disableAutoFocus: true
            }),
          ],
        })

        console.log('Univer instance created:', univerInstance)
        console.log('UniverAPI created:', api)
        
        // 验证 API 是否可用
        if (!api || typeof api.createWorkbook !== 'function') {
          throw new Error('UniverAPI is not properly initialized')
        }
        
        // 注册插件
        console.log('Registering plugins...')
        univerInstance.registerPlugin(ImportCSVPlugin)
        univerInstance.registerPlugin(ImportExcelPlugin)
        univerInstance.registerPlugin(ExportPlugin)
        console.log('Plugins registered successfully')
        
        setUniver(univerInstance)
        setUniverAPI(api)

        // 创建默认工作簿
        console.log('Creating default workbook...')
        api.createWorkbook({
          id: 'default-workbook',
          name: 'Default Workbook',
          sheetOrder: ['sheet1'],
          locale: LocaleType.ZH_CN,
          styles: {},
          sheets: {
            sheet1: {
              id: 'sheet1',
              name: 'Sheet1',
              cellData: {},
              rowCount: 1000,
              columnCount: 20,
              rowHeader: {
                width: 46,
                hidden: 0
              },
              columnHeader: {
                height: 20,
                hidden: 0
              },
              rightToLeft: 0
            }
          }
        })

        // 验证工作簿创建成功
        const workbook = api.getActiveWorkbook()
        if (!workbook) {
          throw new Error('Failed to create default workbook')
        }

        console.log('Univer initialized successfully')
        setIsReady(true)

      } catch (error) {
        console.error('Failed to initialize Univer:', error)
        setIsReady(false)
        setUniver(null)
        setUniverAPI(null)
      }
    }, 2000) // 增加延迟时间到2秒

    return () => {
      console.log('Cleaning up Univer initialization')
      clearTimeout(initTimer)
      if (univer) {
        univer.dispose()
      }
    }
  }, [])

  const actualContainerId = sheetId ? `univer-container-${sheetId}` : containerId

  return (
    <UniverContext.Provider value={{ univer, univerAPI, isReady }}>
      <div 
        ref={containerRef} 
        id={actualContainerId}
        className="w-full h-full"
        style={{ minHeight: '600px', height: '100vh' }}
      >
        {children}
      </div>
    </UniverContext.Provider>
  )
}

export const useUniver = () => {
  const context = useContext(UniverContext)
  if (!context) {
    throw new Error('useUniver must be used within a UniverProvider')
  }
  return context
}
